namespace :radiant do
  namespace :extensions do
    namespace :feedme do
      
      desc "Runs the migration of the Feedme extension"
      task :migrate => :environment do
        require 'radiant/extension_migrator'
        if ENV["VERSION"]
          FeedmeExtension.migrator.migrate(ENV["VERSION"].to_i)
        else
          FeedmeExtension.migrator.migrate
        end
      end
      
      desc "Copies public assets of the Feedme to the instance public/ directory."
      task :update => :environment do
        is_svn_or_dir = proc {|path| path =~ /\.svn/ || File.directory?(path) }
        Dir[FeedmeExtension.root + "/public/**/*"].reject(&is_svn_or_dir).each do |file|
          path = file.sub(FeedmeExtension.root, '')
          directory = File.dirname(path)
          puts "Copying #{path}..."
          mkdir_p RAILS_ROOT + directory
          cp file, RAILS_ROOT + path
        end
      end
      
      desc "Updates local feed's copies as necessary."
      task :update_feeds => :environment do
        Feed.find_all.each do |feed|
          if (feed[:updated_at] + feed[:update_interval]) < Time.now
            puts "Downloading '#{feed[:name]}' feed..."
            feed.update_feed_data
          end
        end
      end

      desc "Updates all local feed's copies."
      task :update_all_feeds => :environment do
        Feed.find_all.each do |feed|
          puts "Downloading '#{feed[:name]}' feed..."
          feed.update_feed_data
        end
      end
      
      desc "Clear all files in tmp/feeds"
      task :clear_feeds => :environment do
        Dir.new(ENV["tmp_feeds_path"]) do |tmp|
          tmp.each do |feed_data|
            puts File.join(ENV["tmp_feeds_path"],feed_data)
          end
        end
      end
    end
  end
end
